<?php

namespace app\shop\library\delivery\implements;

use app\shop\library\delivery\DeliveryInterface;
use app\shop\library\ShopHelper;
use app\shop\library\ShopLogHelper;
use ba\Exception;
use EasyWeChat\MiniApp\Application;
use Throwable;

class WechatImplement implements DeliveryInterface
{
    private Application $app;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $miniappConfig = ShopHelper::get_setting_group('miniapp_config');

        try {
            $this->app = new Application([
                'app_id' => $miniappConfig['miniapp_id'],
                'secret' => $miniappConfig['miniapp_secret'],
            ]);
        } catch (Throwable) {
            throw new Exception('微信小程序物流查询组件异常,请联系管理员');
        }
    }

    public function query(array $params): array
    {
        $options = [
            "openid"         => $params['openid'],
            "waybill_id"     => $params['delivery_no'],
            'receiver_phone' => $params['receiver_phone'],
            'delivery_id'    => $params['delivery_company_code'] ?? '',
        ];

        $result = [];

        try {
            $response     = $this->app->getClient()->postJson("/cgi-bin/express/delivery/open_msg/follow_waybill", $options);
            $waybillToken = $response['waybill_token'] ?? '';

            if (!$waybillToken) {
                ShopLogHelper::error('微信小程序物流查询组件异常', [
                    'params' => $options,
                    'result' => $response
                ]);
                return $result;
            }

            $queryResult = $this->app->getClient()->postJson("/cgi-bin/express/delivery/open_msg/query_follow_trace", [
                'waybill_token' => $waybillToken
            ]);

            $data = $queryResult->toArray();

            if ($data['errcode'] != 0) {
                ShopLogHelper::error('微信物流插件查询物流轨迹异常', [
                    'response' => $data,
                    'options'  => $options,
                ]);

                return $result;
            }

            ShopLogHelper::info('微信物流插件查询物流轨迹结果', [
                'params'   => $params,
                'response' => $data,
            ]);

            return $this->formatData($data);
        } catch (Throwable $e) {
            ShopLogHelper::error('微信小程序物流查询组件异常', [
                'params' => $options,
            ], $e);
            return $result;
        }
    }

    public function formatData(array $data): array
    {
        return array_map(function ($item) {
            return [
                'time'    => date('Y-m-d H:i:s', $item['action_time']),
                'context' => $item['action_msg'],
            ];
        }, $data['waybill_info']['path']['path_action']);
    }
}